// @flow
import React, { Component } from 'react'
import styles from './UserSettingActions.css'
import { Button, Popconfirm, message, Switch } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import md5 from 'md5'

type Props = {
  refreshUserSetting: Function,
  data: Object,
  history: Object,
  current: number,
  pageSize: number
}
type State = {
  freezeFlag: boolean
}

class UserSettingActions extends Component {
  props: Props
  state: State
  deleteUserSetting: Function
  editUserSetting: Function
  resetUserSetting: Function
  freezeUser: Function
  constructor (props: Props) {
    super(props)
    this.deleteUserSetting = this.deleteUserSetting.bind(this)
    this.freezeUser = this.freezeUser.bind(this)
    this.resetUserSetting = this.resetUserSetting.bind(this)
    this.editUserSetting = this.editUserSetting.bind(this)
    this.state = {
      freezeFlag: true
    }
  }
  componentWillMount () {
    const { data } = this.props
    if (data.loginFlag === 1) {
      this.setState({
        freezeFlag: false
      })
    }
  }
  freezeUser () {
    this.setState({
      freezeFlag: !this.state.freezeFlag
    })
    const { data } = this.props
    // $FlowFixMe
    universalFetch(`${__SERVICE_API__}sys/users/${data.id}/freeze?freeFlag=${!this.state.freezeFlag}`,
      {
        method: 'POST'
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('冻结成功')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('冻结失败')
      })
  }

  editUserSetting () {
    const { history, data } = this.props
    universalFetch(`${__SERVICE_API__}sys/users/${data.id}`)
      .then(res => res.json())
      .then((json) => {
        history.push({
          pathname: '/system/user-edit',
          state: {
            data: json.result
          } })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  deleteUserSetting () {
    const { data, current, pageSize } = this.props
    universalFetch(`${__SERVICE_API__}sys/users/${data.id}`, {
      method: 'DELETE'
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.props.refreshUserSetting(current, pageSize)
      message.success('用户删除成功')
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('用户删除失败')
    })
  }
  resetUserSetting () {
    const { data } = this.props
    console.log(data)
    let values = {
      'id': data.id,
      'password': md5('123456')
    }
    universalFetch(`${__SERVICE_API__}sys/users/${data.id}/reset`,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      message.success('重置成功')
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('重置失败')
    })
  }
  render () {
    return (
      <div className={styles['actions']}>
        <Button
          size='small'
          type='primary'
          style={{ marginRight: '10px' }}
          onClick={this.editUserSetting}
          >
          编辑
        </Button>
        <Popconfirm title='确定要删除此用户吗'
          arrowPointAtCenter
          placement='left'
          onConfirm={this.deleteUserSetting}
          >
          <Button
            size='small'
            type='danger'
            >
            删除
          </Button>
        </Popconfirm>
        <Popconfirm title='确定要将此用户密码重置吗，重置后密码为123456'
          arrowPointAtCenter
          placement='left'
          onConfirm={this.resetUserSetting}
          >
          <Button
            size='small'
            >
            密码重置
          </Button>
        </Popconfirm>
        &nbsp;
        <Switch checkedChildren={'已冻结'} unCheckedChildren={'冻结'} onChange={this.freezeUser} defaultChecked={this.state.freezeFlag} />
      </div>
    )
  }
}

export default UserSettingActions
